package org.example.juc.sync;

import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierExample {
    public static void main(String[] args) throws Exception {
        int threadCount = 4;
        CyclicBarrier barrier = new CyclicBarrier(threadCount, () -> {
            System.out.println("All threads reached the barrier.");
        });

        for (int i = 0; i < threadCount - 1; i++) {
            final int threadId = i;
            new Thread(() -> {
                try {
                    Thread.sleep(1000); // 模拟工作
                    System.out.println("Thread " + threadId + " reached the barrier.");
                    barrier.await(); // 等待其他线程
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }
        System.out.println("Main Thread reached the barrier.");
        barrier.await(); // 等待其他线程
        System.out.println("All threads end");
        System.out.println("do something else");
    }
}
